package com.lj.back.manage.scaffold.module.sys.resolver;

import com.lj.back.manage.scaffold.common.enums.ResponseEnum;
import com.lj.back.manage.scaffold.common.enums.UserStatusEnum;
import com.lj.back.manage.scaffold.common.exception.MyException;
import com.lj.back.manage.scaffold.common.util.Assert;
import com.lj.back.manage.scaffold.common.util.HttpRequestUtil;
import com.lj.back.manage.scaffold.module.sys.DTO.SysUserDTO;
import com.lj.back.manage.scaffold.module.sys.annotation.SysLogin;
import com.lj.back.manage.scaffold.module.sys.service.SysLoginService;
import com.lj.back.manage.scaffold.module.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 有@SysLogin注解的方法参数，注入当前登录用户
 * @author lv
 */
@Component
@AllArgsConstructor
public class SysLoginResolver implements HandlerMethodArgumentResolver {

    private final SysUserService userService;

    private final SysLoginService sysLoginService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(SysUserDTO.class) && parameter.hasParameterAnnotation(SysLogin.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory){
        //获取用户ID
        String token = HttpRequestUtil.getToken((HttpServletRequest) request);
        Assert.assertNotNull(token, ResponseEnum.TOKEN_IS_NULL);
        SysUserDTO user = userService.getUserByToken(token);
        if (user == null){
            sysLoginService.logout(token);
            throw new MyException(ResponseEnum.TOKEN_INVALID);
        }
        if (Objects.equals(UserStatusEnum.LOCK.getCode(), user.getStatus())){
            sysLoginService.logout(token);
            throw new MyException(ResponseEnum.LOGIN_USER_LOCK);
        }
        return user;
    }
}
